package com.hbun.cxcy.controller;

import cn.hutool.core.io.FileUtil;
import com.hbun.cxcy.common.utils.R;
import com.hbun.cxcy.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/cxcy/file")
public class FileController {
    //绑定文件上传路径到uploadPath
    @Value("${file.uploadFolder}")
    private String uploadPath;

    @Autowired
    FileService fileService;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");

    @PostMapping("/upload")
    public String uploadFile(HttpServletRequest request,
                             @RequestParam("file") MultipartFile uploadFile) {
        System.out.println(uploadPath);
        // 在 uploadPath 文件夹中通过日期对上传的文件归类保存
        // 比如：/2019/06/06/cf13891e-4b95-4000-81eb-b6d70ae44930.png
        String format = sdf.format(new Date());
//        File folder = new File(uploadPath + format);
//        if (!folder.isDirectory()) {
//            folder.mkdirs();
//        }
        FileUtil.mkdir(uploadPath + format);

        // 对上传的文件重命名，避免文件重名
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString()
                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            // 文件保存
            uploadFile.transferTo(FileUtil.file(uploadPath + format + newName));

            // 返回上传文件的访问路径  http://81.70.28.187:8082/2022/02/07/e484aafc-0da9-4b15-866b-ba8d0895e39f.jpg

            String filePath = request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() + "/" + uploadPath + format + newName;
            return filePath;
        } catch (Exception e) {
            return new Exception("错误").toString();
        }
    }


}